package com.zky.gulimall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zky.common.constant.AuthServerConstant;
import com.zky.common.exception.BizCodeEnum;
import com.zky.common.utils.R;
import com.zky.common.vo.MemberRespVo;
import com.zky.gulimall.authserver.feign.MemberFeignService;
import com.zky.gulimall.authserver.feign.ThirdPartFeignService;
import com.zky.gulimall.authserver.vo.UserLoginVo;
import com.zky.gulimall.authserver.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description 登陆相关
 * @Author 张开源
 * @Date 2022/11/21 15:17
 * @Version 1.0
 **/
@Controller
@Slf4j
public class LoginController {
    @Autowired
    private ThirdPartFeignService partFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {

        //接口防刷

        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            long previous = Long.parseLong(redisCode.split("_")[1]);
            long current = System.currentTimeMillis();
            if(current-previous<60000){
                log.warn("发送时间小于60秒，请60秒后重试");
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        log.warn("code:"+code);
        String value=code+"_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,value,10, TimeUnit.MINUTES);
        R sendCode = partFeignService.sendCode(phone, code, 5);
        if (!sendCode.isSuccess()) {
            throw new RuntimeException("发送异常，result:" + sendCode.getMsg());
        }
        return R.ok();
    }


    @PostMapping("/register")
    public String register(@Valid UserRegisterVo registerVo,
                           BindingResult bindingResult,
                           RedirectAttributes attributes){
        if(bindingResult.hasErrors()){
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(item -> item.getField(), item -> item.getDefaultMessage()));
            log.error("注册异常，result:"+ JSON.toJSONString(errors));
            attributes.addFlashAttribute("errors",errors);
            //有错误则回到注册页
            return "redirect:http://auth.zky.com/reg.html";
        }
        String codeValue = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        Map<String, String> errors = new HashMap<>();
        if(StringUtils.isEmpty(codeValue)){
            log.error("注册异常，result:"+ JSON.toJSONString(errors));
            errors.put("code","验证码已过期");
            attributes.addFlashAttribute("errors",errors);
            //有错误则回到注册页
            return "redirect:http://auth.zky.com/reg.html";
        }
        if(!registerVo.getCode().equalsIgnoreCase(codeValue.split("_")[0])){
            log.error("注册异常，result:"+ JSON.toJSONString(errors));
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            //有错误则回到注册页
            return "redirect:http://auth.zky.com/reg.html";
        }

        //注册
        R register = memberFeignService.register(registerVo);
        if(!register.isSuccess()){
            errors.put("msg",register.getMsg());
            attributes.addFlashAttribute("errors",errors);
            //有错误则回到注册页
            return "redirect:http://auth.zky.com/reg.html";
        }
        //使验证码失效
        redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());

        //注册成功回到登陆页
        return "redirect:http://auth.zky.com/login.html";
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(Objects.isNull(attribute)){
            return "login";
        }
        log.warn("session:"+session.getAttribute(AuthServerConstant.LOGIN_USER));
        return "redirect:http://zky.com";
    }


    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes attributes, HttpSession session){
        log.warn("loginVo:"+loginVo);
        R login = memberFeignService.login(loginVo);
        if(!login.isSuccess()){
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",login.getMsg());
            log.error("登陆异常，result:"+ JSON.toJSONString(errors));
            attributes.addFlashAttribute("errors",errors);
            //登陆失败回到登陆页
            return "redirect:http://auth.zky.com/login.html";
        }
        String data = JSON.toJSONString(login.get("data"));
        MemberRespVo memberRespVo = JSON.parseObject(data, new TypeReference<MemberRespVo>() {
        });
        session.setAttribute(AuthServerConstant.LOGIN_USER,memberRespVo);
        log.warn(" login success,memberRespVo:" + memberRespVo);
        //远程登陆
        return "redirect:http://zky.com";
    }
}
